const [request, crypto, fs, path] = [
  require('request-promise-native'),
  require('crypto'),
  require('fs'),
  require('path')
]
const Diff2html = require('diff2html')

const $ = require('meeko')
const util = require('util')
const execFile = util.promisify(require('child_process').execFile)
const beautify = require('js-beautify').html_beautify

async function req (
  url = url,
  data,
  method = 'POST',
  headers = {
    'Content-Type': 'application/json'
  },
  proxy
) {
  let body = await request({
    method: method,
    url: url,
    responseType: 'json',
    timeout: 5000,
    proxy: proxy,
    headers: headers,
    data: data
  })
  return body
}
function envPath () {
  return process.env.NODE_ENV
    ? '/data/project_v4/weixin-crawl'
    : path.join(__dirname, '../../jt/weixin-doc')
}
let weixinPrex = 'https://developers.weixin.qq.com'
module.exports = {
  async diffList (ctx) {
    const data = ctx.checkedData.data
    ctx.type = 'text/html'
    let r = await execFile('git', [
      '-C',
      envPath(),
      'log',
      '--pretty=format:"%h$%cd"',
      '--since=7.day'
    ])
    let arr = r.stdout.split('\n')
    arr = arr
      .filter(Boolean)
      .map(x => [
        `<a href="diffsimple?hash=${x
          .split('$')[0]
          .replaceAll('"', '')}">${$.tools.timeAgo(
          new Date(x.split('$')[1].replaceAll('"', '')).date2Str(),
          new Date()
        )}</a>`,
        `<a href="diffhtml?hash=${x
          .split('$')[0]
          .replaceAll('"', '')}">${new Date(
          x.split('$')[1].replaceAll('"', '')
        ).date2Str()}</a>`,
        `<a href="diffview?hash=${x
          .split('$')[0]
          .replaceAll('"', '')}">${$.tools.timeAgo(
          new Date(x.split('$')[1].replaceAll('"', '')).date2Str(),
          new Date()
        )}</a>`,
        `<a href="diffview?type=side-by-side&hash=${x
          .split('$')[0]
          .replaceAll('"', '')}">${new Date(
          x.split('$')[1].replaceAll('"', '')
        ).date2Str()}</a>`
      ])
    ctx.body = $.tools.genTemp.genHtml(
      '',
      $.tools.genTemp.gridTable(
        [
          {
            dataTitleArr: [
              '简单模式',
              'web模式比较',
              '代码混合模式比较',
              '代码左右模式比较'
            ],
            dataArr: arr,
            dataTitle: '微信文档差异比较'
          }
        ],
        'open'
      ),
      `<style>
    a:visited {color: #3572b0;}
    a {color: #3572b0;text-decoration: none;}
    </style>`
    )
  },

  async diffView (ctx) {
    const { hash, type } = ctx.checkedData.data
    ctx.type = 'text/html'
    let r = await execFile('git', ['-C', envPath(), 'diff', hash])
    const diffJson = Diff2html.parse(
      unescape(r.stdout.replace(/&#x/g, '%u').replace(/;/g, ''))
    )
    const diffHtml = Diff2html.html(diffJson, {
      drawFileList: true,
      synchronisedScroll: true,
      outputFormat: type, //'side-by-side',
      matching: 'word'
      //matching: 'lines'
    })
    let prefix = `<!DOCTYPE html>
  <html lang="cn">
    <head>
    <meta charset=utf-8" />
      <title></title>
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/diff2html/bundles/css/diff2html.min.css" />  
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/diff2html/bundles/js/diff2html.min.js"></script>
    </head>
    <body>
  `
    let rear = `
    </body>
  </html>`

    ctx.body = prefix + diffHtml + rear
    console.log('env', process.env.NODE_ENV)
  },
  async diffHtml (ctx) {
    const { hash } = ctx.checkedData.data
    ctx.type = 'text/html'

    let commitFile = fs.readFileSync(
      path.join(envPath(), 'temp', hash + '.html')
    )
    ctx.body = commitFile
    return
    let r = await execFile('git', [
      '-C',
      envPath(),
      'diff',
      hash,
      '--diff-filter=AD',
      '--numstat'
    ])
    let addDel = r.stdout.split('\n')
    let addDelArr = []

    addDel
      .filter(x => x.length > 0)
      .map(x => {
        let it = x.split('\t')
        if (it[2].indexOf('weixin-doc') >= 0) {
          addDelArr.push(
            it[2]
              .replaceAll('weixin-doc', weixinPrex)
              .replaceAll('.html.html', '.html')
              .replaceAll('_', '/')
              .replaceAll('//', '/')
          )
        } else {
          addDelArr.push(it[2])
        }
        if (+it[0] === 0) {
          addDelArr.push('D')
        } else {
          addDelArr.push('A')
        }
      })

    r = await execFile('git', [
      '-C',
      envPath(),
      'diff',
      hash,
      '--diff-filter=M',
      '--numstat'
    ])
    let modify = r.stdout.split('\n')
    modify = modify.slice(0, 20)
    let modifyArr = []
    modify = modify
      .filter(x => x.length > 0)
      .map(x => {
        let it = x.split('\t')
        modifyArr.push(it[2])
        modifyArr.push('--')
        modifyArr.push('--')
      })
    let t1 = new Date()
    for (let i = 0; i < modifyArr.length / 3; i++) {
      let commitFile = await execFile('git', [
        '-C',
        process.env.NODE_ENV
          ? path.join(__dirname, '../../jt/weixin-doc')
          : path.join(__dirname, '../../jt/weixin-doc'),
        'show',
        hash + ':' + modifyArr[3 * i]
      ])
      modifyArr[3 * i + 1] = commitFile.stdout
      modifyArr[3 * i + 2] = fs
        .readFileSync(
          process.env.NODE_ENV
            ? path.join(__dirname, '../../jt/weixin-doc')
            : path.join(__dirname, '../../jt/weixin-doc', modifyArr[3 * i])
        )
        .toString()
      modifyArr[3 * i] =
        modifyArr[3 * i].indexOf('weixin-doc') >= 0
          ? modifyArr[3 * i]
              .replaceAll('weixin-doc', weixinPrex)
              .replaceAll('.html.html', '.html')
              .replaceAll('_', '/')
              .replaceAll('//', '/')
          : '#'
    }
    let f = fs
      .readFileSync(path.join(__dirname, '../', 'template', 'htmldiff.html'))
      .toString()
    console.log('读取文件耗时：', new Date() - t1)
    ctx.body = $.tpl(f).render({
      addDel: JSON.stringify(addDelArr),
      modify: JSON.stringify(modifyArr)
    })
  },
  async diffSimple (ctx) {
    const { hash } = ctx.checkedData.data
    ctx.type = 'text/html'
    let r = await execFile('git', [
      '-C',
      envPath(),
      'diff',
      hash,
      '--diff-filter=AD',
      '--numstat'
    ])
    let addDel = r.stdout.split('\n')
    let addDelArr = []

    addDel
      .filter(x => x.length > 0)
      .map(x => {
        let it = x.split('\t')
        if (it[2].indexOf('weixin-doc') >= 0) {
          addDelArr.push(
            it[2]
              .replaceAll('weixin-doc', weixinPrex)
              .replaceAll('.html.html', '.html')
              .replaceAll('_', '/')
              .replaceAll('//', '/')
          )
        } else {
          addDelArr.push(it[2])
        }
        if (+it[0] === 0) {
          addDelArr.push('D')
        } else {
          addDelArr.push('A')
        }
      })

    r = await execFile('git', [
      '-C',
      envPath(),
      'diff',
      hash,
      '--diff-filter=M',
      '--numstat'
    ])
    let modify = r.stdout.split('\n')
    let modifyArr = []
    modify = modify
      .filter(x => x.length > 0)
      .map(x => {
        let it = x.split('\t')
        modifyArr.push(it[2])
        modifyArr.push('')
        modifyArr.push('')
      })
    let t1 = new Date()
    for (let i = 0; i < modifyArr.length / 3; i++) {
      modifyArr[3 * i + 1] = ''
      modifyArr[3 * i + 2] = ''
      modifyArr[3 * i] =
        modifyArr[3 * i].indexOf('weixin-doc') >= 0
          ? modifyArr[3 * i]
              .replaceAll('weixin-doc', weixinPrex)
              .replaceAll('.html.html', '.html')
              .replaceAll('_', '/')
              .replaceAll('//', '/')
          : modifyArr[3 * i]
    }
    let f = fs
      .readFileSync(path.join(__dirname, '../', 'template', 'htmldiff.html'))
      .toString()
    console.log('读取文件耗时：', new Date() - t1)
    ctx.body = $.tpl(f).render({
      addDel: JSON.stringify(addDelArr),
      modify: JSON.stringify(modifyArr)
    })
  }
}

// 扩展函数
